from django.db import models
from django.contrib.auth.models import User


class Genre(models.Model):
    """电影类型模型"""
    name = models.CharField(max_length=100, unique=True, verbose_name="类型名称")
    
    class Meta:
        verbose_name = "电影类型"
        verbose_name_plural = "电影类型"
    
    def __str__(self):
        return self.name


class Movie(models.Model):
    """电影模型"""
    movie_id = models.CharField(max_length=100, unique=True, verbose_name="电影ID")
    title = models.CharField(max_length=500, verbose_name="电影标题")
    genres = models.ManyToManyField(Genre, verbose_name="电影类型")
    year = models.IntegerField(null=True, blank=True, verbose_name="上映年份")
    director = models.CharField(max_length=200, null=True, blank=True, verbose_name="导演")
    description = models.TextField(null=True, blank=True, verbose_name="电影描述")
    poster = models.ImageField(upload_to='movie_posters/', null=True, blank=True, verbose_name="电影海报")
    
    class Meta:
        verbose_name = "电影"
        verbose_name_plural = "电影"
    
    def __str__(self):
        return f"{self.title} ({self.year})"


class Rating(models.Model):
    """评分模型"""
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="用户")
    movie = models.ForeignKey(Movie, on_delete=models.CASCADE, verbose_name="电影")
    rating = models.FloatField(verbose_name="评分")
    timestamp = models.DateTimeField(auto_now_add=True, verbose_name="评分时间")
    
    class Meta:
        verbose_name = "评分"
        verbose_name_plural = "评分"
        unique_together = ('user', 'movie')  # 每个用户对每部电影只能评分一次
    
    def __str__(self):
        return f"{self.user.username} - {self.movie.title}: {self.rating}"


class Comment(models.Model):
    """留言模型"""
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="用户")
    movie = models.ForeignKey(Movie, on_delete=models.CASCADE, verbose_name="电影")
    content = models.TextField(verbose_name="留言内容")
    timestamp = models.DateTimeField(auto_now_add=True, verbose_name="留言时间")
    
    class Meta:
        verbose_name = "留言"
        verbose_name_plural = "留言"
        ordering = ['-timestamp']  # 按时间倒序排列
    
    def __str__(self):
        return f"{self.user.username} - {self.movie.title}: {self.content[:50]}..."
